<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of AdService
 *
 * @author Administrator
 */
class AdService {

    function countAd($location, $enabled = 1) {
        $adTable = D('ad');
        if (!empty($location)) {
            $where['location'] = array('eq', $location);
        }
        $where['enabled'] = array('eq', $enabled);
        return $adTable->where($where)->count();
    }

    function listAd($offset, $limit, $location, $enabled = 1) {
        $adTable = D('ad');
        if (!empty($location)) {
            $where['location'] = array('eq', $location);
        }
        $where['enabled'] = array('eq', $enabled);

        return $adTable->where($where)->limit($offset . ',' . $limit)->order('date desc')->select();
    }

    function listAdByLocation($location, $enabled = 1) {
        $adTable = D('ad');
        $where['location'] = array('eq', $location);
        $where['enabled'] = array('eq', $enabled);

        return $adTable->where($where)->select();
    }

    function insert($ad) {
        D('ad')->data($ad)->add();
    }

    function save($ad) {
        D('ad')->save($ad);
    }

    function findAdByLocation($location, $enabled = 1) {
        $adTable = D('ad');
        $where['location'] = array('eq', $location);
        $where['enabled'] = array('eq', $enabled);

        return $adTable->where($where)->find();
    }

    function deleteByLocation($location) {
        $where['location'] = array('eq', $location);
        $list = D('ad')->where($where)->select();

        foreach ($list as $l) {
            //删除文件
            $filename = str_replace('..', './App/Tpl/default', $l['img_url']);
            if (file_exists($filename)) {
                if (unlink($filename)) {
                    //删除数据库内容
                    $this->delete($l['id']);
                }
            }
            //删除缩略图
            if (file_exists('thumb_' . $filename)) {
                unlink('thumb_' . $filename);
            }
        }
    }

    function delete($id) {
//        $ad = $this->getAdById($id);
//        $ad['enabled'] = 0;

        D('ad')->where(array('id' => $id))->delete();
    }

    function getAdById($id) {
        return D('ad')->find($id);
    }

}

?>
